<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="status">
        <el-tag :class="row.status ? 'successTag' : 'dangerTag'">{{ row.status ? '是' : '否' }}</el-tag>
      </template>
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.classGroup_delete" @click="handleDelete">删 除 </el-button>
        <el-button type="success" size="small" icon="el-icon-setting" v-if="permission.personnelManage_personnel_manage" @click="handleClassManage">班组人员管理</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>
    <el-dialog append-to-body title="班组人员管理" :visible.sync="classGroupManage.visible" @open="open" @close="close" width="60%" top="5vh">
      <avue-crud
        v-model="classGroupManage.form"
        ref="groupCrud"
        :option="classGroupManage.option"
        :table-loading="classGroupManage.loading"
        :data="classGroupManage.data"
        :defaults.sync="classGroupManage.defaults"
        :page.sync="classGroupManage.page"
        :before-open="beforeOpen"
        @selection-change="groupSelectionChange"
        @row-del="groupRowDel"
        @current-change="groupCurrentChange"
        @size-change="groupSizeChange"
        @refresh-change="groupRefreshChange"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddUser">添加人员</el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDelUser">删除人员</el-button>
          <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImportUser">导入</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
    <importDialogComp
      :title="importConfig.title"
      :url="importConfig.url"
      another-export-method
      :export-name="importConfig.exportName"
      :export-code="importConfig.exportCode"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, groupSubmit, groupRemove, getGroupList } from '@/api/admin/classGroup';
import { mapGetters } from 'vuex';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { validateContacts } from '@/mixins/validateContacts.js';
import importDialogComp from '@/components/dialog/import/index.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'AdminClassGroup',
  components: {
    GlobalModalTemplate,
    importDialogComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ADMIN_CLASS_GROUP',
      visibile: false,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {
        principle: '',
        principleName: ''
      },
      importConfig: {
        show: false,
        exportName: '班组人员导入模板.xlsx',
        title: '班组人员导入',
        exportCode: 'MES_SHIFT_GROUP_USER',
        url: '/api/mes-admin/shift-group-user/import-excel'
      },
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        labelWidth: 120,
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '班组编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入班组编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '班组名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入班组名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '所属车间',
            prop: 'workshopName',
            search: true,
            type: 'search',
            disabled: true,
            searchType: 'input',
            rules: [
              {
                required: true,
                message: '请输入所属车间',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({
                type: 'workshop'
              });
            }
          },
          {
            label: '班次',
            prop: 'shiftName',
            type: 'search',
            disabled: true,
            rules: [
              {
                required: true,
                message: '请输入班次',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({
                type: 'shiftName'
              });
            }
          },
          {
            label: '班组人数',
            prop: 'shiftGroupCount',
            disabled: true
          },
          {
            label: '班组负责人',
            prop: 'principleName',
            type: 'search',
            disabled: true,
            searchType: 'input',
            rules: [
              {
                required: true,
                message: '请输入班组负责人',
                trigger: 'blur'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({
                type: 'principleName'
              });
            }
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [{ validator: validateContacts, trigger: 'blur' }]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            value: 1,
            dataType: 'number',
            align: 'center',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            span: 24
          }
        ]
      },
      data: [],
      classGroupManage: {
        visible: false,
        form: {},
        option: {
          height: 500,
          calcHeight: 30,
          maxHeight: 500,
          tip: true,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          addBtn: false,
          editBtn: false,
          viewBtn: false,
          selection: true,
          menuWidth: 100,
          labelWidth: 120,
          dialogClickModal: false,
          column: [
            {
              label: '姓名',
              prop: 'userName'
            },
            {
              label: '登录账号',
              prop: 'userCode'
            },
            {
              label: '角色',
              prop: 'roleName'
            },
            {
              label: '部门',
              prop: 'deptName'
            },
            {
              label: '进入班组时间',
              prop: 'createTime'
            }
          ]
        },
        query: {
          shiftGroupId: ''
        },
        selectionList: [],
        loading: false,
        defaults: {},
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        submitData: null,
        data: []
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.classGroup_add, false),
        viewBtn: this.vaildData(this.permission.classGroup_view, false),
        delBtn: this.vaildData(this.permission.classGroup_delete, false),
        editBtn: this.vaildData(this.permission.classGroup_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    groupIds() {
      let ids = [];
      this.classGroupManage.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['view'].includes(type)) {
        this.defaults.workshopName.type = 'input';
        this.defaults.shiftName.type = 'input';
        this.defaults.principleName.type = 'input';
      } else {
        this.defaults.workshopName.type = 'search';
        this.defaults.shiftName.type = 'search';
        this.defaults.principleName.type = 'search';
      }
      if (['add'].includes(type)) {
        this.defaults.shiftGroupCount.display = false;
      } else {
        this.defaults.shiftGroupCount.display = true;
      }
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data || this.form;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        if (data.records) {
          this.data = data.records;
        }
        this.loading = false;
        this.selectionClear();
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 班组负责人信息
        case 'principleName':
          this.modalName = 'principleNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择班组负责人信息',
            reserveSelection: true,
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'multiple',
            menuWidth: 100,
            templateName: 'USER'
          };
          break;
        // 车间信息
        case 'workshop':
          this.modalName = 'workshopModal';
          this.visibile = true;
          this.tableOption = {
            lazy: true,
            modalTitle: '选择车间信息',
            url: '/api/mes-product/workshop/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'WORKSHOP'
          };
          break;
        // 班次信息
        case 'shiftName':
          this.modalName = 'shiftNameModal';
          this.visibile = true;
          this.tableOption = {
            lazy: true,
            modalTitle: '选择班次信息',
            url: '/api/mes-admin/shift/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'SHIFT'
          };
          break;
        // 班组人员信息
        case 'classGroupPeople':
          this.modalName = 'classGroupPeopleModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择用户（双击进行选择）',
            url: '/api/mes-admin/shift-group-user/user/page',
            isPage: true,
            rowSelectionType: 'multiple',
            selectable: (row, index) => {
              return !this.classGroupManage.data.map((item) => item.userId).includes(row['userId']);
            },
            tip: false,
            menuWidth: 100,
            templateName: 'CLASS_GROUP_USER',
            isToggleSelection: true,
            selectionArray: this.classGroupManage.data.map((item) => item.userId),
            filterKey: 'userId'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principleNameModal':
          this.visibile = false;
          let principleIds = [];
          let principleNames = [];
          this._forEach(rowData, (item) => {
            principleIds.push(item.id);
            principleNames.push(item.realName);
          });
          this.form.principle = principleIds.join(',');
          this.form.principleName = principleNames.join(',');
          break;
        case 'workshopModal':
          this.visibile = false;
          this.form.workshopId = this._get(rowData, 'id', '');
          this.form.workshopName = this._get(rowData, 'name', '');
          break;
        case 'shiftNameModal':
          this.visibile = false;
          this.form.shiftId = this._get(rowData, 'id', '');
          this.form.shiftName = this._get(rowData, 'name', '');
          break;
        case 'classGroupPeopleModal':
          this.visibile = false;
          console.log(rowData);
          let result = rowData.map((row) => {
            return {
              userId: row.userId,
              userName: row.userName,
              userCode: row.userCode,
              roleName: row.roleName,
              deptName: row.deptName,
              createTime: ''
            };
          });
          this.classGroupManage.submitData = result;
          this.submitForm();
          break;
        default:
          break;
      }
    },
    // 班组人员管理
    handleClassManage() {
      if (this.selectionList.length === 0 || this.selectionList.length > 1) {
        this.$message.warning('请选择一条数据');
        return;
      }
      this.classGroupManage.query.shiftGroupId = this.selectionList[0].id;
      this.classGroupManage.visible = true;
    },
    // 班组人员管理 添加人员
    handleAddUser() {
      this.openUserCommonModal({
        type: 'classGroupPeople'
      });
    },
    // 班组人员管理 单个 删除人员
    groupRowDel(row) {
      this.$confirm(`确定将班组：${this.selectionList[0].name}选择人员删除?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (row.id) {
            return groupRemove(row.id);
          } else {
            let findIndex = this.classGroupManage.data.findIndex((group) => group.userId == row.userId);
            if (findIndex > -1) {
              return this.classGroupManage.data.splice(findIndex, 1);
            }
          }
        })
        .then(() => {
          this.groupOnLoad(this.classGroupManage.page, this.classGroupManage.query);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    // 班组人员管理 批量 删除人员
    handleDelUser() {
      if (this.classGroupManage.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm(`确定将班组：${this.selectionList[0].name}选择人员删除?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let isHandleEdit = this.classGroupManage.selectionList.every((group) => group.id);
          if (isHandleEdit) {
            return groupRemove(this.groupIds);
          } else {
            this.classGroupManage.data = this.classGroupManage.data.filter(
              (group) => !this.classGroupManage.selectionList.map((select) => select.userId).includes(group.userId)
            );
          }
        })
        .then(() => {
          this.groupOnLoad(this.classGroupManage.page, this.classGroupManage.query);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.groupCrud.toggleSelection();
        });
    },
    handleImportUser() {
      this.importConfig.show = true;
    },
    codeClose() {},
    groupOnLoad(page, params = {}) {
      this.classGroupManage.loading = true;
      getGroupList(page.currentPage, page.pageSize, Object.assign(params, this.classGroupManage.query)).then((res) => {
        const data = res.data.data;
        this.classGroupManage.page.total = data.total;
        this.classGroupManage.data = data.records;
        this.classGroupManage.loading = false;
        this.groupSelectionClear();
      });
    },
    groupSelectionChange(list) {
      this.classGroupManage.selectionList = list;
    },
    groupSelectionClear() {
      this.classGroupManage.selectionList = [];
      this.$refs.groupCrud.toggleSelection();
    },
    groupRefreshChange() {
      this.groupOnLoad(this.classGroupManage.page, this.classGroupManage.query);
    },
    groupCurrentChange(currentPage) {
      this.classGroupManage.page.currentPage = currentPage;
      this.groupRefreshChange();
    },
    groupSizeChange(pageSize) {
      this.classGroupManage.page.pageSize = pageSize;
      this.groupRefreshChange();
    },
    submitForm() {
      let groupUser = this.classGroupManage.submitData.map((group) => {
        return {
          shiftGroupId: this.selectionList[0].id,
          userCode: group.userCode,
          userId: group.userId,
          userName: group.userName
        };
      });
      groupSubmit(groupUser).then(() => {
        this.groupOnLoad(this.classGroupManage.page, this.classGroupManage.query);
        this.$message({
          type: 'success',
          message: `班组：${this.selectionList[0].name}人员添加成功!`
        });
      });
    },
    open() {
      this.groupOnLoad(this.classGroupManage.page, this.classGroupManage.query);
    },
    close() {
      this.classGroupManage.visible = false;
      this.onLoad(this.page);
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
